package panda.record;

import static java.sql.Types.*;

import panda.buffer.PageFormatter;
import panda.file.Block;
import panda.file.Page;

public class RecordFormatter implements PageFormatter {
	private TableToken tableToken;

	public RecordFormatter(TableToken tableToken) {
		this.tableToken = tableToken;
	}

	public void format(Page page) {
		// System.out.println("*********************");
		int recordSize = tableToken.getTupleLength() + Page.INT_SIZE * 2;
		for (int pos = Page.INT_SIZE * 2; pos + recordSize < Block.BLOCK_SIZE; pos += recordSize) {
			page.putInt(pos, 0);
			for (String attribute : tableToken.getSchema()
					.getAllAttributeNames()) {
				int offset = tableToken.offsetOf(attribute);
				if (tableToken.getSchema().getType(attribute) == INTEGER)
					page.putInt(pos + Page.INT_SIZE * 2 + offset, 0);
				else
					page.putString(pos + Page.INT_SIZE * 2 + offset, "");
			}
		}

		page.putInt(0, Page.INT_SIZE * 2);
		int offset = Page.INT_SIZE * 2;
		while (offset + 2 * recordSize < Block.BLOCK_SIZE) {
			page.putInt(offset + Page.INT_SIZE, offset + recordSize);
			offset += recordSize;
		}
		page.putInt(offset + Page.INT_SIZE, 0);
		// System.out.println("*********************\n");
	}
}
